import React, { createContext, useContext, useMemo, useState } from "react";
import { Application } from "../Core";

export interface IAppContext {
    config: AppView.IRootAppOptions;
    application: Application;
    deviceType: AppView.IDeviceType;
}

export const AppContext = createContext({});

export const Provider = ({ children, config, ...others }: any) => {
    const [ ConfigData ] = useState<AppView.IRootAppOptions>(config);
    const appContext = useMemo(() => {
        return {
            config: ConfigData,
            i18n: others.i18n,
        };
    }, [ConfigData]);
    const RenderChildren = children ? React.cloneElement(children, others) : <></>;
    return <AppContext.Provider value={appContext}>
        { ConfigData.ServiceProvider ? <ConfigData.ServiceProvider>{RenderChildren}</ConfigData.ServiceProvider> : RenderChildren }
        { !ConfigData.ServiceProvider ? <>{RenderChildren}</> : <></> }
    </AppContext.Provider>;
};

export const useApp = () => {
    const appContext = useAppContext();
    return appContext.application
};

export const createProvider = (config: AppView.IRootAppOptions) => {
    return {
        AppProvider: (props: any) => <Provider {...props} config={config}/>,
        useApp
    };
};

export const useAppContext = (): IAppContext => useContext<any>(AppContext);
